// Copyright 2022 The Liquigo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package config

import (
	. "gitee.com/west0207/liquigo/core/log"
	utils "gitee.com/west0207/liquigo/core/utils"

	yaml "gopkg.in/yaml.v2"
)

// app.yml
type Yaml struct {
	DB []DB `yaml:"db,flow"`
}

// entry-xml: [entry-xxxx-app01.xml]
// driver-name: sqlite
// data-source-name: D:\dev\learn\db
// dbms-name: sqlite
// dbms-version: 3
type DB struct {
	EntryXml       []string `yaml:"entry-xml,flow"`
	DriverName     string   `yaml:"driver-name"`
	DataSourceName string   `yaml:"data-source-name"`
	DbmsName       string   `yaml:"dbms-name"`
	DbmsVersion    string   `yaml:"dbms-version"`
}

// 获取app.yml配置
// yamlfile string 配置文件名称
func GetYamlConfig(yamlfile string) ([]DB, error) {
	yamlFileBytes, err := utils.GetFileBytes(&yamlfile)
	if err != nil {
		// 获取文件的字节数组失败
		Sug.Errorf("Failed to get byte array of file %v，error: %v", yamlfile, err)
		panic(err)
	}

	conf := Yaml{}
	err = yaml.Unmarshal(yamlFileBytes, &conf)
	if err != nil {
		// 解析文件的失败
		Sug.Errorf("Failed to parse file %v，error: %v", yamlfile, err)
		panic(err)
	}
	for i := range conf.DB {
		if conf.DB[i].DbmsName == utils.EMPTY {
			// DbmsName默认值为DriverName
			conf.DB[i].DbmsName = conf.DB[i].DriverName
		}
	}
	return conf.DB, nil
}
